#include <sys/epoll.h>
#include <cstring>
#include <unistd.h>
#include "Log.hpp"

static const int epoll_size = 64;

class Epoll
{
public:
    Epoll()
    {}
    ~Epoll()
    {
        if(_epfd >- 0)
        {
            close(_epfd);
        }
    }
    void InitEpoll(int size = epoll_size)
    {
        _epfd = epoll_create(size);
        if(_epfd < 0) 
        {
            ELOG("epoll_create error, erron: %d, strerror: %s", errno, strerror(errno));
            exit(2);
        }
        else ILOG("epoll_create success ...");
    }

    void AddEvent(int fd, uint32_t events)
    {
        struct epoll_event ev;
        ev.events = events;
        ev.data.fd = fd;
        int ret = epoll_ctl(_epfd, EPOLL_CTL_ADD, fd, &ev);
        if(ret < 0)
        {
            ELOG("AddEvent error, fd: %d, events: %u", fd, events);
            exit(3);
        }
        ILOG("AddEvent success ...");
    }
    void DelEvent(int fd)
    {
        epoll_ctl(_epfd, EPOLL_CTL_DEL, fd, nullptr);
    }

    int Wait(struct epoll_event *ev, int nums, int timeout)
    {
        return epoll_wait(_epfd, ev, nums, timeout);
    }

private:
    int _epfd;
};